package org.jeecg.modules.api.wlhy.debang.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DictUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.api.wlhy.app.bean.ResBaseBean;
import org.jeecg.modules.api.wlhy.app.utils.HttpUtils;
import org.jeecg.modules.api.wlhy.debang.bean.DeBangRequest;
import org.jeecg.modules.api.wlhy.debang.bean.DeBangResponse;
import org.jeecg.modules.api.wlhy.debang.bean.DeBangUrlRequest;
import org.jeecg.modules.api.wlhy.debang.bean.DeBangVehicle;
import org.jeecg.modules.api.wlhy.debang.entity.DbOrder;
import org.jeecg.modules.api.wlhy.debang.entity.DbOrderReq;
import org.jeecg.modules.api.wlhy.debang.service.IDbOrderService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wlhy.hyarea.service.IHyAreaService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

import static org.springframework.beans.BeanUtils.copyProperties;

/**
 * @Description: db_order
 * @Author: jeecg-boot
 * @Date: 2023-08-12
 * @Version: V1.0
 */
@Api(tags = "db_order")
@RestController
@RequestMapping("/debang/dbOrder")
@Slf4j
public class DbOrderController extends JeecgController<DbOrder, IDbOrderService> {
    @Autowired
    private IDbOrderService dbOrderService;

    @Autowired
    private DictUtil dictUtil;

    @Autowired
    private IHyAreaService hyAreaService;

    @Value(value = "${debang.username:1}")
    private String DBUSERNAME;

    @Value(value = "${debang.password:1}")
    private String DBPASSWORD;

    @Value(value = "${debang.phone:1}")
    private String DBPHONE;

    /**
     * 分页列表查询
     *
     * @param dbOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "db_order-分页列表查询", notes = "db_order-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(DbOrder dbOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<DbOrder> queryWrapper = QueryGenerator.initQueryWrapper(dbOrder, req.getParameterMap());
//        queryWrapper.eq("order_stauts","-1");
        Page<DbOrder> page = new Page<DbOrder>(pageNo, pageSize);
        IPage<DbOrder> pageList = dbOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }
    /**
     * 分页列表查询
     *
     * @param dbOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "db_order-分页列表查询", notes = "db_order-分页列表查询")
    @GetMapping(value = "/zbList")
    public Result<?> queryPageZBList(DbOrder dbOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<DbOrder> queryWrapper = QueryGenerator.initQueryWrapper(dbOrder, req.getParameterMap());
        queryWrapper.eq("order_stauts","1");
        Page<DbOrder> page = new Page<DbOrder>(pageNo, pageSize);
        IPage<DbOrder> pageList = dbOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param dbOrder
     * @return
     */
    @AutoLog(value = "db_order-添加")
    @ApiOperation(value = "db_order-添加", notes = "db_order-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody DbOrder dbOrder) {
        dbOrderService.save(dbOrder);
        return Result.OK("添加成功！");
    }

    /**
     * 德邦推送数据
     *
     * @param
     * @return
     */
    @AutoLog(value = "db_order-添加")
    @ApiOperation(value = "db_order-添加", notes = "db_order-添加")
    @PostMapping(value = "/dbadd")
    public Result<?> dbadd(@RequestBody DeBangResponse response) {
        if (response.getRequestEntity() == null) {
            return Result.error("推送实体为空！");
        }
        log.error("德邦推送订单信息:"+response);



        DbOrderReq dbOrder = response.getRequestEntity();

//        JSONObject jsonObject = dictUtil.parseObjectDict(response.getRequestEntity());

        dbOrder.setType(response.getType());
        DbOrder order =new DbOrder();




        String[] sfdsplit = dbOrder.getDepartureName().split("\\|");
        String sfdsplit1 = hyAreaService.getAreaNames(sfdsplit[0]+"000000");
        String sfdsplit2 = hyAreaService.getAreaNames(sfdsplit[1]+"000000");
        dbOrder.setDepartureName(sfdsplit1+"|"+sfdsplit2);

        String[] mddsplit = dbOrder.getArrivalsName().split("\\|");
        String mddsplit1 = hyAreaService.getAreaNames(mddsplit[0]+"000000");
        String mddsplit2 = hyAreaService.getAreaNames(mddsplit[1]+"000000");
        dbOrder.setDepartureName(mddsplit1+"|"+mddsplit2);

        copyProperties(dbOrder,order);

        order.setPlatformcode(DBUSERNAME);
        order.setCiphertxt(DBPASSWORD);
        order.setServicePhone(DBPHONE);


        List<DeBangVehicle> cars = dbOrder.getCars();
        String carStr="";
        for (int i = 1; i < cars.size(); i++) {
            carStr=carStr+i+",需求车辆长:"+cars.get(i).getModels()+"需求车辆类型:"+cars.get(i).getBoxType()+",";
        }
        order.setCars(carStr);

        if (response.getType().equals("ORDERSTAUTS")) {
            dbOrderService.updateById(order);
        }else{
            dbOrderService.save(order);
        }
        return Result.OK("成功！");
    }


    /**
     * 报价
     *
     * @param dbOrder
     * @return
     */
    @AutoLog(value = "db_order-报价")
    @ApiOperation(value = "db_order-报价", notes = "db_order-报价")
    @PostMapping(value = "/baojia")
    public Result<?> baojia(@RequestBody DbOrder dbOrder) throws IOException {
//        DbOrder dbOrderReq = dbOrderService.getById(dbOrder.getId());


        dbOrderService.updateById(dbOrder);
        DeBangUrlRequest request=new DeBangUrlRequest();
        dbOrder.setUniqueId(dbOrder.getId());
        dbOrder.setFailuretime(dbOrder.getFailuretime().replace("-","/"));
        request.setRequestEntity(dbOrder);
        request.setMsgId("OPEN_API_1000002");
        log.error("请求德邦报价接口:"+JSON.toJSONString(request));
        String res = HttpUtils.sendDeBang("http://openapi.deppon.com.cn:11169/tps-driver-api/rest/api/v1/open", JSON.toJSONString(request));
        log.error("德邦报价接口返回:"+res);
        DeBangRequest resBaseBean = JSONObject.parseObject(res, DeBangRequest.class);
        if(resBaseBean.getErrCode().equals("1")){
            dbOrder.setOrderStatus("1");
            dbOrder.setOrderStauts("1");
            dbOrderService.updateById(dbOrder);
            return Result.OK("报价成功！");
        }else{
            dbOrder.setOrderStatus(resBaseBean.getResponseEntity().getErrCodes());
            dbOrder.setOrderStauts(resBaseBean.getResponseEntity().getErrCodes());
            dbOrderService.updateById(dbOrder);
            return Result.OK("报价失败！");
        }
//        dbOrderService.save(dbOrder);
    }

    /**
     * 编辑
     *
     * @param dbOrder
     * @return
     */
    @AutoLog(value = "db_order-编辑")
    @ApiOperation(value = "db_order-编辑", notes = "db_order-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody DbOrder dbOrder) {
        dbOrderService.updateById(dbOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "db_order-通过id删除")
    @ApiOperation(value = "db_order-通过id删除", notes = "db_order-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        dbOrderService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "db_order-批量删除")
    @ApiOperation(value = "db_order-批量删除", notes = "db_order-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.dbOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "db_order-通过id查询", notes = "db_order-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        DbOrder dbOrder = dbOrderService.getById(id);
        if (dbOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(dbOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param dbOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DbOrder dbOrder) {
        return super.exportXls(request, dbOrder, DbOrder.class, "db_order");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DbOrder.class);
    }

}
